package com.springbootsecuritydemo.handler;

import com.alibaba.fastjson.JSONObject;
import com.springbootsecuritydemo.utils.WebUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权异常处理
 *
 * @Author Daft_V
 * @Date 2022/5/3 14:15
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 403);
        map.put("msg", "无权限访问此资源");
        JSONObject jsonObject = new JSONObject(map);
        //异常处理
        WebUtil.renderString(httpServletResponse, jsonObject.toJSONString());
    }
}
